/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * StaffView.java
 *
 * Created on 19-jan-2010, 10:19:19
 */
package View;

import Util.GenericTableModel;
import Controller.Controller;
import Model.Flight;
import Model.Staff;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Jeroen
 */
public class StaffView extends javax.swing.JInternalFrame implements Observer {

    /**
     * Creates new form StaffView
     */
    public StaffView() {
        initComponents();
        tblStaff.setAutoCreateRowSorter(true);
        Controller.Instance().addObserver(this);
        fillTable();
    }

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof Staff) {
            fillTable();
        }
    }

    private void fillTable() {
        GenericTableModel<Staff> ptm = new GenericTableModel<>(Controller.Instance().getStaff());
        tblStaff.setModel(ptm);
        GenericTableModel.removeColumn(tblStaff, "password");
        GenericTableModel.removeColumn(tblStaff, "rank");
        GenericTableModel.removeColumn(tblStaff, "id");


    }

    private void fillTable(ArrayList<Staff> staff) {
        GenericTableModel<Staff> ptm = new GenericTableModel<>(staff);
        tblStaff.setModel(ptm);
        GenericTableModel.removeColumn(tblStaff, "password");
        GenericTableModel.removeColumn(tblStaff, "rank");
        GenericTableModel.removeColumn(tblStaff, "id");


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnReset = new javax.swing.JButton();
        btnCreate = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        txtSearch = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblStaff = new javax.swing.JTable();
        lblError = new javax.swing.JLabel();
        btnClose = new javax.swing.JButton();
        chbCaseSensitive = new javax.swing.JCheckBox();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flyaway.FlyAWayApp.class).getContext().getResourceMap(StaffView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setVerifyInputWhenFocusTarget(false);

        btnReset.setText(resourceMap.getString("btnReset.text")); // NOI18N
        btnReset.setName("btnReset"); // NOI18N
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnCreate.setText(resourceMap.getString("btnCreate.text")); // NOI18N
        btnCreate.setName("btnCreate"); // NOI18N
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        btnUpdate.setText(resourceMap.getString("btnUpdate.text")); // NOI18N
        btnUpdate.setName("btnUpdate"); // NOI18N
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnDelete.setText(resourceMap.getString("btnDelete.text")); // NOI18N
        btnDelete.setName("btnDelete"); // NOI18N
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        txtSearch.setName("txtSearch"); // NOI18N
        txtSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSearchKeyReleased(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblStaff.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblStaff.setName("tblStaff"); // NOI18N
        jScrollPane1.setViewportView(tblStaff);

        lblError.setName("lblError"); // NOI18N

        btnClose.setText(resourceMap.getString("btnClose.text")); // NOI18N
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        chbCaseSensitive.setText(resourceMap.getString("chbCaseSensitive.text")); // NOI18N
        chbCaseSensitive.setName("chbCaseSensitive"); // NOI18N
        chbCaseSensitive.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                chbCaseSensitiveItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnReset, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                            .addComponent(btnClose, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(11, 11, 11))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                            .addComponent(btnCreate, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                            .addComponent(btnUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(chbCaseSensitive))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnReset)
                    .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chbCaseSensitive))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnDelete))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnClose)
                        .addContainerGap())))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCreate, btnReset});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        final CreateChangeStaffView ccsv = new CreateChangeStaffView(null);
        flyaway.FlyAWayApp app = (flyaway.FlyAWayApp) flyaway.FlyAWayApp.getApplication();
        app.getFlyAwayView().addFrame(ccsv);
    }//GEN-LAST:event_btnCreateActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        int selected = tblStaff.getSelectedRow();
        if (selected >= 0) {
            GenericTableModel<Staff> staffModel = (GenericTableModel<Staff>) tblStaff.getModel();
            final CreateChangeStaffView ccsv = new CreateChangeStaffView(staffModel.getRow(tblStaff.convertRowIndexToModel(selected)));
            flyaway.FlyAWayApp app = (flyaway.FlyAWayApp) flyaway.FlyAWayApp.getApplication();
            app.getFlyAwayView().addFrame(ccsv);
        } else {
            lblError.setText("Please select a row first");
        }
    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed

        boolean delete = true;
        
        int selected = tblStaff.getSelectedRow();
        if (selected >= 0) {
            GenericTableModel<Staff> staffModel = (GenericTableModel<Staff>) tblStaff.getModel();
            Staff staff = staffModel.getRow(tblStaff.convertRowIndexToModel(selected));
        
            ArrayList<Flight> flightlist = Controller.Instance().getFlights();
            
            for(int i = 0 ; i < flightlist.size() ; i++){
                
                Flight FlightToChck = flightlist.get(i) ;
                
                if( FlightToChck.getPilot() == staff || FlightToChck.getCopilot() == staff){
                   delete = false;     
                }
                
            }
            
            if(delete){
            Controller.Instance().delete(staff);
            JOptionPane.showMessageDialog(this, "User \"" + staff.getUsername() + "\" deleted");
            }else{
                JOptionPane.showMessageDialog(null, "Deze staff member bevind zich al op een vlucht","kan niet deleten" ,JOptionPane.WARNING_MESSAGE);
            }
        } else {
            if(!delete){lblError.setText("This staffmember is already on a flight");}
            lblError.setText("Please select a row first");
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        this.lblError.setText("");
        this.txtSearch.setText("");
        this.fillTable();
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed
    private void searchStaff() {
        String searchString = txtSearch.getText();
        ArrayList<Staff> foundStaff = new ArrayList<>();

        if (searchString.isEmpty()) {
            fillTable();
        } else {
            int searchId = -1;
            try {
                searchId = Integer.parseInt(searchString);
            } catch (NumberFormatException nfe) {
                Logger.getLogger(GenericTableModel.class.getName()).log(Level.FINER, null, nfe.getMessage());
            }

            if (searchId != -1) {
                foundStaff.addAll(Controller.Instance().searchStaff(searchId));
            } else {
                if (chbCaseSensitive.isSelected()) {
                    foundStaff.addAll(Controller.Instance().searchStaff(searchString, true));
                } else {
                    foundStaff.addAll(Controller.Instance().searchStaff(searchString, false));
                }
            }
            fillTable(foundStaff);
        }
    }
    private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSearchKeyReleased
        searchStaff();
    }//GEN-LAST:event_txtSearchKeyReleased

    private void chbCaseSensitiveItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_chbCaseSensitiveItemStateChanged
        searchStaff();
    }//GEN-LAST:event_chbCaseSensitiveItemStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JCheckBox chbCaseSensitive;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblError;
    private javax.swing.JTable tblStaff;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
}
